package com.yinhai.model;

import java.io.File;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.test.UiThreadTest;
import android.text.SpannableString;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.listener.MsgTextListener;
import com.listener.MsgTextLongClickListener;
import com.lz.util.Utils;
import com.yinhai.activity.ChatActivity;
import com.yinhai.activity.OnlineContactDetailActivity;
import com.yinhai.activity.R;
import com.yinhai.constant.UrlConstant;
import com.yinhai.photo.utils.Photo;
import com.yinhai.service.MsgServiceImpl;
import com.yinhai.util.NullUtils;

public class ChatMsgViewAdapter extends BaseAdapter {
    
    MsgServiceImpl msgservive = null;
    
    private List<ChatMsgEntity> coll;
    
    private ChatActivity ctx;
    
    private LayoutInflater mInflater;
    
    private boolean isGroup;
    
    ChatMsgEntity entity;
    
    GestureDetector gestureDetector;
    
    public ChatActivity content;
    
    private AQuery aq = null;
    
    public static interface IMsgViewType {
        int IMVT_COM_MSG = 0;
        
        int IMVT_TO_MSG = 1;
    }
    
    public ChatMsgViewAdapter() {
    }
    
    public ChatMsgViewAdapter(ChatActivity context, List<ChatMsgEntity> list, boolean isGroup) {
        this.ctx = context;
        this.coll = list;
        this.isGroup = isGroup;
        mInflater = LayoutInflater.from(context);
        msgservive = new MsgServiceImpl(context);
    }
    
    @Override
    public int getCount() {
        return coll.size();
    }
    
    @Override
    public Object getItem(int position) {
        return coll.get(position);
    }
    
    @Override
    public long getItemId(int position) {
        return position;
    }
    
    @Override
    public int getItemViewType(int position) {
        entity = coll.get(position);
        
        if (entity.getMsgType()) {
            return IMsgViewType.IMVT_COM_MSG;
        } else {
            return IMsgViewType.IMVT_TO_MSG;
        }
    }
    
    @Override
    public int getViewTypeCount() {
        return 2;
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        entity = coll.get(position);
        MsgModel msg = msgservive.getMsgModelByUUID(entity.getUuid());
        boolean isComMsg = entity.getMsgType();
        
        ViewHolder viewHolder = new ViewHolder();
        if (isComMsg) {
            convertView = mInflater.inflate(R.layout.chatting_item_msg_text_left, null);
            
        } else {
            convertView = mInflater.inflate(R.layout.chatting_item_msg_text_right, null);
        }
        
        viewHolder.tvSendTime = (TextView)convertView.findViewById(R.id.tv_sendtime);
        viewHolder.tvUserName = (TextView)convertView.findViewById(R.id.tv_username);
        viewHolder.tvContent = (TextView)convertView.findViewById(R.id.tv_chatcontent);
        viewHolder.iv_userhead = (ImageView)convertView.findViewById(R.id.iv_userhead);
        viewHolder.iv_userhead.setTag(msg.getSendUserId());
        viewHolder.contentLayout = (FrameLayout)convertView.findViewById(R.id.lv_content_layout);
        viewHolder.contentLayout.setClickable(true);
        viewHolder.contentLayout.setOnClickListener(new MsgTextListener(entity.getType(), msg, entity, ctx));
        viewHolder.contentLayout.setOnLongClickListener(new MsgTextLongClickListener(entity.getType(), msg, ctx));
        viewHolder.isComMsg = isComMsg;
        viewHolder.tv_isreceipt = (ImageView)convertView.findViewById(R.id.tv_isreceipt);
        viewHolder.iv_contentImage = (ImageView)convertView.findViewById(R.id.tv_pic);
        viewHolder.tvSend = (TextView)convertView.findViewById(R.id.iv_cf);
        convertView.setTag(viewHolder);
        
        aq = new AQuery(convertView);
        
        if (entity.getType().equals("2") || entity.getType().equals("4")) {
            viewHolder.iv_contentImage.setVisibility(View.VISIBLE);
            viewHolder.tvContent.setVisibility(View.GONE);
        } else {
            viewHolder.iv_contentImage.setVisibility(View.GONE);
            viewHolder.tvContent.setVisibility(View.VISIBLE);
        }
        
        if (isComMsg) {
            
 
            viewHolder.iv_userhead.setOnClickListener(new View.OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    Intent it = new Intent(ctx, OnlineContactDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("userId", v.getTag().toString());
                    it.putExtras(bundle);
                    ctx.startActivity(it);
                }
            });
            aq.id(R.id.iv_userhead).image(UrlConstant.LOCAL_URI + "getPhoto?phone=" + msg.getSendUserId(),
                Utils.getImageOptions(ctx, R.drawable.tel_photo, Utils.IsImgSize));
        } else {
            aq.id(R.id.iv_userhead).image(UrlConstant.LOCAL_URI + "getPhoto?phone=" + msg.getSendUserId(),
                Utils.getImageOptions(ctx, R.drawable.tel_photo, Utils.IsImgSize));
        }
        
        String name = entity.getIsreceipt() == null ? "1" : entity.getIsreceipt().toString();
        if (isGroup) {
            viewHolder.tv_isreceipt.setImageResource(0);
        } else {
            if (name.equals("0")) {
                viewHolder.tv_isreceipt.setImageResource(R.drawable.ic_chat_lt_1);
            } else {
                viewHolder.tv_isreceipt.setImageResource(R.drawable.ic_chat_lt_2);
            }
        }
        
        viewHolder.tvSend.setTag(entity);
        viewHolder.tvSend.setOnClickListener(ctx.SendItem);
        if(entity.getMsgModel().getStatus() !=null && !"".equals(entity.getMsgModel().getStatus())){
            int status =Integer.parseInt(entity.getMsgModel().getStatus());
            if(status == 3){
                viewHolder.tvSend.setVisibility(View.VISIBLE);
                viewHolder.tv_isreceipt.setImageResource(0);
            }else{
                viewHolder.tvSend.setVisibility(View.INVISIBLE);
            }
        }
        
        
        viewHolder.tvContent.setCompoundDrawables(null, null, null, null); // 清空左图标
        viewHolder.tvContent.setCompoundDrawablePadding(0);
        
        viewHolder.tvSendTime.setText(entity.getDate());
        viewHolder.tvUserName.setText(msg.getSendUserName());
        // 图片、位置
        if (entity.getType().equals("2") || entity.getType().equals("4")) {
            
            File f = new File(Photo.getSaveIMPicPath(), msg.getUuid() + ".png");
            if (f.exists()) {
                //Bitmap imageBitmap = BitmapFactory.decodeFile(Photo.getSaveIMPicPath() + msg.getUuid() + ".png");
                Bitmap imageBt = Photo.zoomImg(BitmapFactory.decodeFile(Photo.getSaveIMPicPath() + msg.getUuid() + ".png"), com.yinhai.util.Utils.dip2px(ctx, 100), ctx);
                if (imageBt!=null&&!imageBt.isRecycled()) {
                    viewHolder.iv_contentImage.setImageBitmap(imageBt);
                }
           
            } else if (NullUtils.isNotEmpty(msg.getFileName())) {
                aq.id(R.id.tv_pic).image(msg.getFileName(),
                    Utils.getImageOptions(ctx, R.drawable.default_avatar_big, 0));
            } else {
                if (entity.getType().equals("2")) {
                    viewHolder.iv_contentImage.setImageResource(R.drawable.default_avatar_big);
                } else if (entity.getType().equals("4")) {
                    viewHolder.iv_contentImage.setImageResource(R.drawable.mapdemo);
                }
                
            }
        } else if (entity.getSpStr() != null && !entity.getType().equals("2")) {
            
            viewHolder.tvContent.setText(entity.getSpStr());
            
        } else {
            if (entity.getType().equals("1")) {
                
                String str = msg.getContent(); // 消息具体内容
                String zhengze = "f0[0-9]{2}|f10[0-7]"; // 正则表达式，用来判断消息内是否有表情
                try {
                    SpannableString spannableString = ExpressionUtil.getExpressionString(ctx, str, zhengze);
                    viewHolder.tvContent.setText(spannableString);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
            }
        }
        
        return convertView;
    }
    
    static class ViewHolder {
        public TextView tvSendTime;
        
        public TextView tvUserName;
        
        public TextView tvContent;
        
        public ImageView tv_isreceipt;
        
        public ImageView iv_userhead;
        
        public ImageView iv_contentImage;
        
        public boolean isComMsg = true;
        
        public FrameLayout contentLayout;
        
        public TextView tvSend;
    }
    
}
